import { watch } from 'vue'
import { userPermissionStore } from '../store/userRoleStore.js'

export default {
  install(app) {
    const store = userPermissionStore()

    app.directive('permission', {
      mounted(el, binding) {
        const { menuId, action } = binding.value
        const parent = el.parentNode
        const placeholder = document.createComment('v-permission')
        let inserted = true

        const update = () => {
          const perms = store.userPermissionData[menuId] || []
          if (!perms.includes(action)) {
            if (inserted && parent) {
              parent.replaceChild(placeholder, el)
              inserted = false
            }
          } else {
            if (!inserted && parent) {
              parent.replaceChild(el, placeholder)
              inserted = true
            }
          }
        }

        // watch store.userPermissionData 的变化
        watch(
          () => store.userPermissionData,
          update,
          { deep: true, immediate: true }
        )
      }
    })
  }
}